package com.gbdata.zuul.filter;

import com.gbdata.zuul.wrapper.ContentCapturingResponseWrapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 修改服务端接口返回的filter
 */
@Component
public class ResponseModifyingFilter extends ZuulFilter {

    @Override
    public String filterType() {
        // 指定过滤器在请求后运行
        return "post";
    }

    @Override
    public int filterOrder() {
        // 设置过滤器顺序
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        // 是否执行过滤器的标识，true表示执行
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletResponse response = ctx.getResponse();
        ContentCapturingResponseWrapper wrappedResponse = null;
        try {
            wrappedResponse = new ContentCapturingResponseWrapper(response);
        } catch (IOException e) {
            e.printStackTrace();
        }

        int status = response.getStatus();
        try {
            // 修改响应内容
            if (status == 307 ) {
                // 可以在这里获取响应内容
                String responseContent = wrappedResponse.getContent();

                // 最后将包装器的内容刷新到原始响应中
                wrappedResponse.copyToResponse(response.getOutputStream());
            }

        } catch (Exception e) {
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(500);
            ctx.setResponseBody(e.getMessage());
        }

        return null;
    }


}
